package com.zekdot.aptgateway.fliter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.zekdot.aptgateway.util.CheckResult;
import com.zekdot.aptgateway.util.ConfigInfo;
import com.zekdot.aptgateway.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Create by zekdot on 20-3-24.
 */
public class JoinMethodFilter extends ZuulFilter {

    @Autowired
    private ConfigInfo configInfo;
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 2;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        // 黑名单
        List<String> regUserDenyList = configInfo.regUserDenyList;
        System.out.println(request.getRequestURL());
        // 黑名单找出不需要登录的url
        for(String regUserDenyUrl:regUserDenyList){
            System.out.println(regUserDenyUrl);
            System.out.println(request.getRequestURL().toString().contains(regUserDenyUrl));
            // 如果在黑名单内
            if(request.getRequestURL().toString().contains(regUserDenyUrl)){
                HttpServletResponse response = ctx.getResponse();
                response.setContentType("text/html;charset=UTF-8");

//                String status = request.getParameter("status");
//                System.out.println(status);
//                if(status == null || !status.equals("success")){
//                    return null;
//                }
                // 从参数列表中取出token对应的值
                String token = request.getParameter("token");
//                if(token == null){
//                    return null;
//                }
                CheckResult checkResult = JwtUtil.validateJWT(token);
                System.out.println(checkResult.isSuccess());
                Claims claims = checkResult.getClaims();
                System.out.println("管理员身份为" + claims.get("identify"));
                // 获取身份
                Integer joinMet = (Integer) claims.get("joinMet");
                System.out.println("身份是" + joinMet);
                // 如果不是正式用户
                if(joinMet != 1){
                    ctx.setSendZuulResponse(false);
                    try {
                        // 返回结果
                        response.getWriter().println(JwtUtil.JWT_NOT_FORM);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                return null;
            }
        }
        return null;
    }
}
